<template>
	<div>
		<!-- 面包屑导航区 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
		  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
		</el-breadcrumb>
		
		<!-- 卡片视图区域 -->
		<el-card>
			<!-- 警告提示 区域 -->
			<el-alert
			    title="注意:只允许为第三级分类设置相关参数!"
			    type="warning" :closable="false"
				show-icon>
			</el-alert>
			
			<!-- 选择商品分类 区域 -->
			<el-row class="cat_opt">
				<el-col>
					<span>选择商品分类:</span>
					
					<!-- 级联选择框区域 -->
					<el-cascader
					    v-model="selectedCateKeys" :options="catelist" :props="cateProps"
					    @change="handleChange">
					</el-cascader>
				</el-col>
			</el-row>
			
			<!-- Tabs页签 区域 -->
			 <el-tabs v-model="activeName" @tab-click="handleTabClick">
				 
				<!-- 动态参数 面板 -->
			    <el-tab-pane label="动态参数" name="many">
					
					<!-- 按钮 -->
					<el-button type="primary" size="mini"
					:disabled="isBtnDisabled" 
					@click="addDialogVisible = true">添加参数</el-button>
					
					<!-- 表格 -->
					<el-table :data="manyTableData" border stripe>
						
						<!-- 展开 列 -->
						<el-table-column type="expand">
							<!-- 作用域插槽 -->
							<template slot-scope="scope">
								
								<!-- Tag标签 -->
								<el-tag v-for="(item, i) in scope.row.attr_vals"
								:key="i" closable
								@close="handleClose(i, scope.row)">{{item}}</el-tag>
								
								<!-- 添加按钮/文本输入框 -->
								<el-input
								  class="input-new-tag"
								  v-if="scope.row.inputVisible"
								  v-model="scope.row.inputValue"
								  ref="saveTagInput"
								  size="small"
								  @keyup.enter.native="handleInputConfirm(scope.row)"
								  @blur="handleInputConfirm(scope.row)">
								</el-input>
								<el-button 
								v-else class="button-new-tag" size="small" 
								@click="showInput(scope.row)">+ New Tag</el-button>
							</template>
						</el-table-column>
						
						<!-- 索引 列 -->
						<el-table-column type="index"></el-table-column>
						<!-- 参数名称 列 -->
						<el-table-column label="参数名称" prop="attr_name"></el-table-column>
						<!-- 操作 列 -->
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button 
									type="primary" icon="el-icon-edit"
									size="mini" @click="showEditDialog(scope.row.attr_id)">
									编辑
								</el-button>
								<el-button 
									type="danger" icon="el-icon-delete"
									size="mini" @click="removeParams(scope.row.attr_id)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				
				<!-- 静态属性 面板 -->
			    <el-tab-pane label="静态属性" name="only">
					<!-- 按钮 -->
					<el-button type="primary" size="mini"
					:disabled="isBtnDisabled"
					@click="addDialogVisible = true">添加属性</el-button>
					
					<!-- 表格 -->
					<el-table :data="onlyTableData" border stripe>
						
						<!-- 展开 列 -->
						<el-table-column type="expand">
							<!-- 作用域插槽 -->
							<template slot-scope="scope">
								
								<!-- Tag标签 -->
								<el-tag v-for="(item, i) in scope.row.attr_vals"
								:key="i" closable
								@close="handleClose(i, scope.row)">{{item}}</el-tag>
								
								<!-- 添加按钮/文本输入框 -->
								<el-input
								  class="input-new-tag"
								  v-if="scope.row.inputVisible"
								  v-model="scope.row.inputValue"
								  ref="saveTagInput"
								  size="small"
								  @keyup.enter.native="handleInputConfirm(scope.row)"
								  @blur="handleInputConfirm(scope.row)">
								</el-input>
								<el-button 
								v-else class="button-new-tag" size="small" 
								@click="showInput(scope.row)">+ New Tag</el-button>
							</template>
						</el-table-column>
						
						<!-- 索引 列 -->
						<el-table-column type="index"></el-table-column>
						<!-- 属性名称 列 -->
						<el-table-column label="属性名称" prop="attr_name"></el-table-column>
						<!-- 操作 列 -->
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button 
									type="primary" icon="el-icon-edit"
									size="mini" @click="showEditDialog(scope.row.attr_id)">
									编辑
								</el-button>
								<el-button 
									type="danger" icon="el-icon-delete"
									size="mini" @click="removeParams(scope.row.attr_id)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			 </el-tabs>
			  
		</el-card>
		
		<!-- 添加参数 对话框 -->
		<el-dialog
		  :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%"
		  @close="addDialogClosed">
		  
		  <!-- 表单区域 -->
		  <el-form 
			:model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
		    <el-form-item :label="titleText" prop="attr_name">
		      <el-input v-model="addForm.attr_name"></el-input>
		    </el-form-item>
		  </el-form>
		  
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addParams">确 定</el-button>
		  </span>
		</el-dialog>
		
		<!-- 编辑 对话框 -->
		<el-dialog
		  :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%"
		  @close="editDialogClosed">
		  
		  <!-- 表单区域 -->
		  <el-form 
			:model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
		    <el-form-item :label="titleText" prop="attr_name">
		      <el-input v-model="editForm.attr_name"></el-input>
		    </el-form-item>
		  </el-form>
		  
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="editDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="editParams">确 定</el-button>
		  </span>
		</el-dialog>
		
		
	</div>
</template>

<script>
	export default {
		name: 'Params',
		data(){
			return {
				catelist: [],  //商品分类的列表数据
				cateProps: {  //级联选择框的配置对象
					expandTrigger: 'hover',
					value: 'cat_id',
					label: 'cat_name',
					children: 'children'
				},
				selectedCateKeys: [],  //级联选择框中选中的值
				activeName: 'many',  //当前激活的页签页，默认为"动态参数"标签页
				manyTableData: [],  //动态参数数据
				onlyTableData: [],  //静态参数数据
				addDialogVisible: false,  //添加对话框的显示和隐藏
				addForm: {  //添加参数对话框中的表单
					attr_name: ''
				},
				addFormRules: {  //添加表单的验证规则对象
					attr_name: [
						{ required: true, message: '请填写参数名称', trigger: 'blur' }
					]
				},
				editDialogVisible: false,  //编辑对话框的显示和隐藏
				editForm: {  //编辑表单的绑定对象
				},
				editFormRules:{  //编辑表单的验证规则对象
					attr_name: [
						{ required: true, message: '请填写参数名称', trigger: 'blur' }
					]
				},
				
			}
		},
		created(){
			//获取所有商品分类的列表数据
			this.getCateList()
		},
		computed: {
			//如果按钮需要被禁用，则返回true，否则返回false
			isBtnDisabled(){
				if(this.selectedCateKeys.length !== 3) {
					return true
				}
				return false
			},
			//当前选中的三级分类的id
			cateId(){
				if(this.selectedCateKeys.length === 3){
					return this.selectedCateKeys[2]
				}
				return null
			},
			//动态计算对话框标题文本
			titleText(){
				if(this.activeName === 'many'){
					return '动态参数'
				}else{
					return '静态属性'
				}
			},
			
		},
		methods: {
			//获取所有商品分类的列表数据
			async getCateList(){
				const {data: res} = await this.$http.get('categories')
				
				if(res.meta.status !== 200){
					return this.$message.error('获取商品分类数据失败！')
				}
				
				this.catelist = res.data
				//console.log(this.catelist)
				
			},
			//级联选择框选中项变化，会触发这个函数
			handleChange(){
				this.getParamsData()
				
				
			},
			//Tabs页签点击事件的回调函数
			handleTabClick(){
				//打印一下当前激活的页签的名称
				//console.log(this.activeName)
				
				this.getParamsData()
			},
			//获取参数的列表数据
			async getParamsData(){
				//console.log(this.selectedCateKeys)
				if(this.selectedCateKeys.length !== 3){
					this.selectedCateKeys = []
					
					//清空参数列表
					this.manyTableData = []
					this.onlyTableData = []
					
					return
				}
				
				//console.log(this.selectedCateKeys)
				
				//根据所选分类的Id，和当前所处的面板，获取对应的参数
				const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,
				{params: {sel: this.activeName}})
				
				if(res.meta.status !== 200){
					return this.$message.error('获取参数列表失败！')
				}
				
				//console.log(res.data)
				
				//字符串转换为数组
				res.data.forEach(item => {
					item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [],
					
					//添加一个字段，用来控制文本框的显示和隐藏,默认不显示
					item.inputVisible = false
					
					//添加一个字段用来接收文本框中输入的内容，默认为空
					item.inputValue = ''
				})
				console.log(res.data)
				
				//根据
				if(this.activeName === 'many'){
					this.manyTableData = res.data
				}else{
					this.onlyTableData = res.data
				}
			},
			//添加参数对话框 close事件的回调
			addDialogClosed(){
				//重置表单
				this.$refs.addFormRef.resetFields()
			},
			//添加参数对话框 确认按钮 click事件 的回调
			addParams(){
				this.$refs.addFormRef.validate(async valid => {
					if(!valid) return 
					
					//发生网络请求，提交数据
					const {data: res} = await this.$http.post(`categories/${this.cateId}
					/attributes`,{
						attr_name: this.addForm.attr_name,
						attr_sel: this.activeName,
					})
					
					if(res.meta.status !== 201){
						return this.$message.error('添加参数失败！')
					}
					
					this.$message.success('添加参数成功')
					
					//关闭对话框
					this.addDialogVisible = false
					
					//刷新数据列表
					this.getParamsData()
				})
			},
			//编辑按钮 click事件的回调函数
			async showEditDialog(attr_id){
				//发起网络请求，获取参数的信息
				const {data: res} = await this.$http.get(`categories/
				${this.cateId}/attributes/${attr_id}`,
				{params: {attr_sel: this.activeName}})
				
				if(res.meta.status !== 200){
					return this.$message.error('获取参数信息失败！')
				}
				
				//将参数的信息保存到data中
				this.editForm = res.data
				
				//显示编辑对话框
				this.editDialogVisible = true
			},
			//编辑对话框 close事件的回调
			editDialogClosed(){
				//重置表单
				//清空修改表单绑定的数据对象
				this.$refs.editFormRef.resetFields()
			},
			//编辑对话框 确认按钮 click事件的回调 
			editParams(){
				this.$refs.editFormRef.validate(async valid => {
					const {data: res} = await this.$http.put(`categories/
					${this.cateId}/attributes/${this.editForm.attr_id}`, 
					{
						attr_name: this.editForm.attr_name,
						attr_sel: this.activeName,
					})
					
					if(res.meta.status !== 200){
						return this.$message.error('修改参数失败！')
					}
					
					this.$message.success('修改参数成功')
					
					
					//刷新数据列表
					this.getParamsData()
					
					//关闭对话框
					this.editDialogVisible = false
				})
			},
			//删除按钮 click事件 的回调
			async removeParams(attr_id){
				const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).catch(err => err)
				
				if(confirmResult !== 'confirm'){
					return this.$message.info('已取消删除')
				}
				
				const {data: res} = await this.$http.delete(`categories/${this.cateId}
				/attributes/${attr_id}`)
				
				if(res.meta.status !== 200){
					return this.$message.error('删除参数失败！')
				}
				
				this.$message.success('删除参数成功')
				
				//刷新数据列表
				this.getParamsData()
			},
			//文本输入框失去焦点或enter键时的回调函数
			handleInputConfirm(row){
				if(row.inputValue.trim().length === 0){
					row.inputValue = ''
					
					//隐藏添加按钮
					row.inputVisible = false
					
					return
				}
				
				row.attr_vals.push(row.inputValue.trim())
				row.inputValue = ''
				row.inputVisible = false
				
				//发起网络请求，让后台保存对attr_vals的修改
				this.saveAttrVals(row)
			},
			//展开列中 可选项的添加按钮 click事件 的回调
			showInput(row){
				//显示文本输入框
				row.inputVisible = true
				
				//让文本框自动获取焦点
				this.$nextTick(_ => {
				  this.$refs.saveTagInput.$refs.input.focus();
				});
			},
			//可选项tab标签 close事件的回调函数
			handleClose(i, row){
				//删除可选项
				row.attr_vals.splice(i, 1)
				
				//发起网络请求，让后台保存对attr_vals的修改
				this.saveAttrVals(row)
				
			},
			//将后台保存用户对参数的可选项的修改代码封装成一个公共的方法
			async saveAttrVals(row){
				//发起网络请求
				const {data: res} = await this.$http.put(`categories/${this.cateId}
				  /attributes/${row.attr_id}`, {
					  attr_name: row.attr_name,
					  attr_sel: row.attr_sel,
					  attr_vals: row.attr_vals.join(' ')
				  })
				
				if(res.meta.status !== 200){
					return this.$message.error('修改参数失败！')
				}
				
				this.$message.success('修改参数成功')
			},
			
		}
	}
</script>

<style lang="less" scoped="scoped">
	.cat_opt {
		margin: 15px 0;
	}
	.el-tag {
		margin: 5px;
	}
	.input-new-tag {
		width: 150px;
	}
</style>

